﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.CompilerServices;
using System.Security.Permissions;

namespace Artem.Web.Security.Store {

    /// <summary>
    /// 
    /// </summary>
    public partial class XmlProfileStore : Persistable<List<XmlProfile>> {

        #region Properties  /////////////////////////////////////////////////////////////

        /// <summary>
        /// Gets the profiles.
        /// </summary>
        /// <value>The profiles.</value>
        public virtual List<XmlProfile> Profiles {
            get { return base.Value ?? (base.Value = new List<XmlProfile>()); }
        }
        #endregion

        #region Construct  //////////////////////////////////////////////////////////////

        /// <summary>
        /// 
        /// </summary>
        public XmlProfileStore(string fileName)
            : base(fileName) {
        }

        /// <summary>
        /// 
        /// </summary>
        protected XmlProfileStore()
            : base(null) {
        }
        #endregion

        #region Methods /////////////////////////////////////////////////////////////////

        /// <summary>
        /// Gets the user by key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public XmlProfile GetByUserKey(Guid key) {

            lock (SyncRoot) {
                return (Profiles != null)
                    ? Profiles.Find(delegate(XmlProfile profile) { return (profile.UserKey.CompareTo(key) == 0); })
                    : null;
            }
        }

        /// <summary>
        /// Gets the name of the by user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        public XmlProfile GetByUserName(string userName) {

            MembershipUser user = Membership.GetUser(userName);
            return (user != null) ? GetByUserKey((Guid)user.ProviderUserKey) : null;
        }

        /// <summary>
        /// Removes the name of the by user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        public void RemoveByUserName(string userName) {

            lock (SyncRoot) {
                XmlProfile profile = GetByUserName(userName);
                if (profile != null)
                    Profiles.Remove(profile);
            }
        }
        #endregion
    }
}
